﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using ChinaScope.CSF.Common.BaseClasses;

namespace ChinaScope.CSF.Common
{
    /// <summary>
    /// 通用帮助类
    /// </summary>
    public static class Common
    {
        //发布状态（0为删除，1为未发布，2为已审核，3为已发布）
        public enum ReleaseStatus
        {
            Del = 0,
            UnPublish = 1,
            Audited = 2,
            Published = 3
        }

        /// <summary>
        /// 删除状态
        /// </summary>
        public enum DelStatus
        {
            notdel = 1,
            del = 0
        }

        /// <summary>
        /// 编辑状态
        /// </summary>
        public enum EditStatus
        {
            edit = 1,
            unedit = 0
        }

        /// <summary>
        /// 把list转换为str(用逗号分开)
        /// </summary>
        public static string ConverListToStr(List<string> ancestors)
        {
            string ancestorstr = string.Empty;
            if (ancestors.Count > 0)
            {

                foreach (var ancestor in ancestors)
                {
                    ancestorstr += ancestor + ",";
                }
                ancestorstr = ancestorstr.Substring(0, ancestorstr.LastIndexOf(","));
            }
            return ancestorstr;
        }

        /// <summary>
        /// 把str转换为list(用逗号分开的)
        /// </summary>
        public static List<string> ConverStrToList(string path)
        {
            List<string> ancestors = new List<string>();
            if (path.Contains((",")))
            {
                string[] arr = path.Split(',');
                for (int i = 0; i < arr.Length; i++)
                {
                    ancestors.Add(arr[i]);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(path))
                    ancestors.Add(path);
            }
            return ancestors;
        }

        /// <summary>
        /// 把list转换为str(用分号分开)
        /// </summary>
        public static string ConverListToStrBySC(List<string> ancestors)
        {
            string ancestorstr = string.Empty;
            if (ancestors.Count > 0)
            {

                foreach (var ancestor in ancestors)
                {
                    ancestorstr += ancestor + ";";
                }
                ancestorstr = ancestorstr.Substring(0, ancestorstr.LastIndexOf(";"));
            }
            return ancestorstr;
        }

        /// <summary>
        /// 把str转换为list(用分号分开的)
        /// </summary>
        public static List<string> ConverStrToListBySC(string path)
        {
            List<string> ancestors = new List<string>();
            if (path.Contains((";")))
            {
                string[] arr = path.Split(';');
                for (int i = 0; i < arr.Length; i++)
                {
                    ancestors.Add(arr[i]);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(path))
                    ancestors.Add(path);
            }
            return ancestors;
        }

        /// <summary>
        /// 将所有字符串用","连接起来
        /// </summary>
        public static string ConbineCondition(params string[] args)
        {
            string conbinestr = string.Empty;
            foreach (string arg in args)
            {
                conbinestr = conbinestr + arg + ",";
            }
            conbinestr = conbinestr.Substring(0, conbinestr.LastIndexOf(","));
            return conbinestr;
        }

        /// <summary>
        /// 将字符串转换为时间格式（三种格式）
        /// 20131130
        /// 2013-11-30
        /// 2013/11/30
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime ConverStrToDate(string argDatestr)
        {
            DateTime ds = new DateTime();//初始化
            //直接转换
            if (argDatestr.Contains('-') || argDatestr.Contains('/'))
            {
                if (DateTime.TryParse(argDatestr, out ds))
                    return ds;
            }
            else
            {
                //全是数字要求为8为，不足的时候用0补齐
                if (argDatestr.Length == 8 && Regex.Match(argDatestr, "^[0-9]*$").Success)
                {
                    //拆分
                    int year = Convert.ToInt32(argDatestr.Substring(0, 4));
                    int month = Convert.ToInt32(argDatestr.Substring(4, 2));
                    int day = Convert.ToInt32(argDatestr.Substring(6, 2));
                    ds = new DateTime(year, month, day);
                }
            }
            return ds;
        }

        /// <summary>
        /// 生成唯一键序列号
        /// </summary>
        public static string GenerateStringID()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
            {
                i *= ((int)b + 1);
            }
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }

        /// <summary>
        /// 根据环境得到指定模块的服务地址
        /// </summary>
        /// <param name="enviro">用户集成登录的环境</param>
        /// <param name="servicename">访问的服务名称（接口名称）</param>
        /// <returns>服务接口名</returns>
        public static string GetServiceUrlByES(string enviro, string servicename)
        {
            string enviroServiceNmae = "";
            switch (enviro)
            {
                case "qa":
                    enviroServiceNmae = "qa_" + servicename;
                    break;
                case "internal":
                    enviroServiceNmae = "internal_" + servicename;
                    break;
                case "dev":
                    enviroServiceNmae = "dev_" + servicename;
                    break;
            }
            return enviroServiceNmae;
        }

        /// <summary>
        /// 读取User节点内容
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public static User GetUserFromFile(string path)
        {
            try
            {
                User user = new User();
                XElement systembuffer = XElement.Load(path);

                if (systembuffer.Element("User") != null)
                {

                    if (systembuffer.Element("User").Attribute("name") != null)
                    {
                        user.Name = systembuffer.Element("User").Attribute("name").Value;
                    }


                    if (systembuffer.Element("User").Attribute("pwd") != null)
                    {
                        user.PassWord = systembuffer.Element("User").Attribute("pwd").Value;
                    }


                    if (systembuffer.Element("User").Attribute("environment") != null)
                    {
                        user.Environment = systembuffer.Element("User").Attribute("environment").Value;
                    }


                    if (systembuffer.Element("User").Attribute("role") != null)
                    {
                        user.Role = Int32.Parse(systembuffer.Element("User").Attribute("role").Value);
                    }

                    if (systembuffer.Element("User").Attribute("code") != null)
                    {
                        user.Code = systembuffer.Element("User").Attribute("code").Value;
                    }

                }

                return user;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 写发布日志
        /// </summary>
        /// <param name="ServiceURL">发布地址</param>
        /// <param name="returnStr">发布参数</param>
        public static void WriteLog(string ServiceURL, string returnStr)
        {
            string rootpath = System.AppDomain.CurrentDomain.BaseDirectory + "Log.txt";
            if (!File.Exists(rootpath))
            {
                FileStream fs = new FileStream(rootpath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                fs.Close();
            }
            StreamWriter sw = new StreamWriter(rootpath, true);
            sw.WriteLine("发布服务调用开始时间：" + DateTime.Now);
            sw.WriteLine("发布服务调用接口：" + ServiceURL);
            sw.WriteLine("发布服务返回结果：" + returnStr);
            sw.WriteLine();
            sw.WriteLine();
            sw.WriteLine(
                "==================================================================================================");
            sw.Close();
        }

        /// <summary>  
        /// 创建GET方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>  
        /// <returns></returns>  
        public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent,
            CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.UserAgent =
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            ServicePointManager.DefaultConnectionLimit = 20;
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            //if (cookies != null)
            //{
            //    request.CookieContainer = new CookieContainer();
            //    request.CookieContainer.Add(cookies);
            //}

            using (var response = (HttpWebResponse) request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.RequestTimeout)
                {
                    return null;
                }
                return response;
            }
        }

        /// <summary>
        /// 将json字符串转换为有效的对象
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="jsonstring">json字符串</param>
        /// <returns>对象</returns>
        public static T Parse<T>(string jsonstring) where T : new()
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonstring)))
            {
                try
                {
                    return (T) new DataContractJsonSerializer(typeof (T)).ReadObject(ms);
                }
                catch (Exception exception)
                {
                    return new T();
                }
            }
        }

        /// <summary>
        /// 发布状态的显示
        /// </summary>
        public static Dictionary<int, string> DiffPublishStatus = new Dictionary<int, string>{
            {1,"未发布"},
            {2,"已审核"},
            {3,"已发布"},
            {0,"已删除"}
        };

        /// <summary>
        /// 发布状态的显示
        /// </summary>
        public static List<int> SupplyTyps = new List<int>
        {
            11,
            12,
            13,
            21,
            22,
            23,
            31,
            32,
            33
        };

        public const string SzhYes = "是"; //是否
        public const string SzhNo = "否";
        public const int IntYes = 1; //是
        public const int IntNo = 0;//否
        public const string EnYes = "YES"; //是否
        public const string EnNo = "NO";
        public const string SHTong = "沪股通"; //沪股通
        public const string HKTong = "港股通"; //港股通
    }

    /// <summary>
    /// 转换汇率的java接口返回的对象
    /// </summary>
    public class JavaServiceModel
    {
        public string code { get; set; }
        public string type { get; set; }

        public List<string> message { get; set; }

    }

    public static class Parent2ChildDemo
    {
        public static TChild Parent2Child<TParent, TChild>(TParent parent) where TChild : TParent, new()
        {
            var child = new TChild();
            var parentType = typeof(TParent);
            var properties = parentType.GetProperties();
            foreach (var propertie in properties)
            {
                //循环遍历属性
                if (propertie.CanRead && propertie.CanWrite)
                {
                    //进行属性拷贝
                    propertie.SetValue(child, propertie.GetValue(parent, null), null);
                }
            }
            return child;
        }

        public static List<TChild> Parents2Childs<TParent, TChild>(List<TParent> parents) where TChild : TParent, new()
        {
            // ReSharper disable ConvertClosureToMethodGroup
            if (parents != null)
                return parents.Select(parent => Parent2Child<TParent, TChild>(parent)).ToList();
            // ReSharper restore ConvertClosureToMethodGroup
            else
            {
                return null;
            }
        }

    }

    public static class Child2ParentDemo
    {
        public static TParent Childs2Parent<TParent, TChild>(TChild child)
            where TChild : TParent, new()
            where TParent : new()
        {
            var parent = new TParent();
            var childType = typeof(TParent);
            var properties = childType.GetProperties();
            foreach (var propertie in properties)
            {
                //循环遍历属性
                if (propertie.CanRead && propertie.CanWrite)
                {
                    //进行属性拷贝
                    propertie.SetValue(parent, propertie.GetValue(child, null), null);
                }
            }
            return parent;
        }

        public static List<TParent> Childs2Parents<TParent, TChild>(List<TChild> childs)
            where TChild : TParent, new()
            where TParent : new()
        {
            // ReSharper disable ConvertClosureToMethodGroup
            return childs.Select(child => Childs2Parent<TParent, TChild>(child)).ToList();
            // ReSharper restore ConvertClosureToMethodGroup
        }

        public static bool IsContainsChinese(this string CString)
        {
            return Regex.IsMatch(CString, @"[\u4e00-\u9fa5]");
        }


    }
}
